#!/usr/bin/env python
import subprocess
import re

try:  
    import pygtk
    pygtk.require("2.0")  
except:  
    pass  
try:  
    import gtk  
except:  
    print("GTK Not Availible")
    sys.exit(1)

class osx86():
	def about_dialog(self, widget):
		self.about = gtk.AboutDialog()
		atext=gtk.Label("Made by SMX.\n")
		apic=gtk.Image()
		self.about.vbox.pack_start(atext)
		self.about.show_all()
		self.about.run()
		self.about.hide()

	def err(self, message):
		err = gtk.MessageDialog(self, gtk.DIALOG_MODAL, 
				gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, message)
		err.connect("response",self.quit)
		self.hide()
		result = err.run()
		
	def warn(self, message):
		warn = gtk.MessageDialog(self.container, gtk.DIALOG_MODAL, 
				gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message)
		warn.run()
		warn.hide()
		
	def check_command(self, command):
		cmd="type -P "+command+" &>/dev/null 2>&1"
		result = subprocess.call(["type", "-P", command], shell=True)
		return result

	def startup(self, widget):
		self.populate_drivelist(drivelist)

	def show_all_ticked(self, widget):
		if widget.get_active():
			self.warn("Warning, Installing on your Hard Drive will wipe ALL DATA!")
		self.drivelist.emit("sort-column-changed")

	def set_mode(self, radiobutton):
		if radiobutton.get_group() == None:
			self.combo.set_available(False)
		else:
			self.combo.set_available(True)

	def populate_drivelist(self, widget):
		showfixed = self.combo.get_active()
		self.drivelist.clear()
		if self.check_command("udisks"):
			self.err("usisks command missing!")
		disks=subprocess.Popen(["udisks", "--enumerate"],stdout=subprocess.PIPE).stdout.readlines()
		for line in disks:
			line=subprocess.Popen(["basename",line],stdout=subprocess.PIPE).stdout.readlines()[0].replace('\n','')
			r=re.compile(".*[0-9]")
			if not r.match(line):
				isrem=int(open("/sys/block/"+line+"/removable", "r").read()[0])
				print showfixed
				if isrem or showfixed:
					ud = subprocess.Popen(["udisks", "--show-info", "/dev/"+line], stdout=subprocess.PIPE)
					grep = subprocess.Popen(["grep", "model"], stdin=ud.stdout, stdout=subprocess.PIPE)
					ud.stdout.close() #make sure we close the output so p2 doesn't hang waiting for more input
					model = str(grep.communicate()[0]).replace('\n','').replace('\t','').replace('model:','').lstrip() #run our commands
					self.drivelist.append(["/dev/"+line+" - "+model])
			
		#widget.append(["CIAO"])
	def __init__(self):
		#super(osx86,self).__init__()
		window = gtk.Window()
		window.set_default_size(700, -1)
		
		button_about=gtk.ToolButton(gtk.STOCK_ABOUT)
		button_about.set_label("About")
		button_about.set_is_important(True)
		button_about.connect("clicked", self.about_dialog)
		
		show_all = gtk.CheckButton("Show all Drives")
		
		drivelist = gtk.ListStore(str)
		drivelist.connect("sort-column-changed", self.populate_drivelist)
		
		sorted = gtk.TreeModelSort(drivelist)

		show_all.connect("toggled", self.show_all_ticked)
		
		button_refresh=gtk.ToolButton(gtk.STOCK_REFRESH)
		button_refresh.set_label("Update Drive List")
		button_refresh.set_is_important(True)
		button_refresh.connect("clicked", self.populate_drivelist)
		button_refresh.connect("show", self.populate_drivelist)
		
		button_img = gtk.Button()
		button_img.set_label("Choose Image")
		
		button_useimg = gtk.RadioButton(None, "Use Image")
		button_usedrive = gtk.RadioButton(button_useimg, "Use Drive")
		button_useimg.connect("toggled", self.set_mode)
		button_usedrive.connect("toggled", self.set_mode)
		
		combo = gtk.ComboBox(sorted)
		cell = gtk.CellRendererText()
		combo.pack_start(cell, True)
		combo.add_attribute(cell, 'text', 0)
		
		table = gtk.Table(10,9)
		
		toolbar = gtk.Toolbar()
		toolbar.insert(button_refresh,0)
		toolbar.insert(button_about, 1)
		
		#window.connect("realize",self.populate_drivelist, drivelist)
		window.connect("destroy", self.quit)
		
		table.attach(toolbar,0,10,0,1)
		table.attach(button_usedrive, 0, 2, 1, 2)
		table.attach(button_useimg, 4, 6, 1, 2)
		table.attach(button_img,0,2,2,3)
		table.attach(combo,0,5,3,4)
		table.attach(show_all,5,7,2,3)
		table.set_homogeneous(True)
		
		window.add(table)
		window.set_resizable(False)
		window.set_size_request(700,400)
		
		self.button_about = button_about
		self.show_all = show_all
		self.drivelist = drivelist
		self.button_refresh = button_refresh
		self.button_img = button_img
		self.button_usedrive = button_usedrive
		self.combo = combo
		self.cell = cell
		self.table = table
		self.container = window
		
		window.show_all()
		
	def quit(self, widget, *data):
		gtk.main_quit()
		
osx86()
gtk.main()